import https from 'https';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import zlib from 'zlib';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
async function fetchPlayerCardData(uid) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'api.lelaer.com',
      path: `/ys/getPlayerCard.php?uid=${uid}&server=cn_gf01&unionid=ohAccuCto54MIXc-IHVqJPohFp7w&from=refresh&timestamp=1744260660743&authkey=fdd1246d01f570e8dfc81877e6b317ba&count=4`,
      method: 'GET',
      headers: {
        'Host': 'api.lelaer.com',
        'Connection': 'keep-alive',
        'xweb_xhr': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c33)XWEB/13487',
        'Content-Type': 'application/json',
        'Accept': '*/*',
        'Sec-Fetch-Site': 'cross-site',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Dest': 'empty',
        'Referer': 'https://servicewechat.com/wx2ac9dce11213c3a8/350/page-frame.html',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9'
      }
    };

    const req = https.request(options, (res) => {
      let rawData = Buffer.alloc(0);
      let responseStream = res;

      // 处理压缩响应
      const encoding = res.headers['content-encoding'];
      if (encoding === 'gzip') {
        responseStream = res.pipe(zlib.createGunzip());
      } else if (encoding === 'br') {
        responseStream = res.pipe(zlib.createBrotliDecompress());
      }

      responseStream.on('data', (chunk) => {
        rawData = Buffer.concat([rawData, chunk]);
      });

      responseStream.on('end', () => {
        try {
          const parsedData = JSON.parse(rawData.toString('utf8'));
          resolve(parsedData);
        } catch (e) {
          reject(new Error(`JSON解析失败: ${e.message}`));
        }
      });
    });

    req.on('error', reject);
    req.end();
  });
}

// 2. 然后定义数据加载和保存函数
async function loadPlayerData() {
    const filePath = path.join(__dirname, 'playercard.json');
    try {
        if (fs.existsSync(filePath)) {
            const data = await fs.promises.readFile(filePath, 'utf8');
            return JSON.parse(data) || [];
        }
    } catch (error) {
        console.error('读取playercard.json失败:', error);
    }
    return [];
}

async function savePlayerData(data) {
    const filePath = path.join(__dirname, 'playercard.json');
    const tempPath = `${filePath}.tmp`;
    try {
        await fs.promises.writeFile(tempPath, JSON.stringify(data, null, 2));
        await fs.promises.rename(tempPath, filePath);
    } catch (error) {
        console.error('保存数据失败:', error);
        throw error;
    }
}

// 3. 定义数据比较和更新函数
function isSameRole(role1, role2) {
    return JSON.stringify(role1) === JSON.stringify(role2);
}

function updateRoleData(existingRoles, newRoles) {
    const updatedRoles = [...existingRoles];
    
    for (const newRole of newRoles) {
        const existingIndex = existingRoles.findIndex(r => r.role === newRole.role);
        if (existingIndex >= 0) {
            if (!isSameRole(existingRoles[existingIndex], newRole)) {
                updatedRoles[existingIndex] = newRole;
            }
        } else {
            updatedRoles.push(newRole);
        }
    }
    
    return updatedRoles;
}

// 4. 主更新函数
export async function updatePlayerCardData(uid) {
    try {
        const newData = await fetchPlayerCardData(uid);
        if (!newData?.result?.role_data?.length) {
            throw new Error('获取的数据格式不正确');
        }
        
        const targetUid = newData.result.role_data[0].uid;
        const existingData = await loadPlayerData();
        
        const playerIndex = existingData.findIndex(
            item => item?.result?.role_data?.[0]?.uid === targetUid
        );
        
        if (playerIndex === -1) {
            existingData.push(newData);
        } else {
            const existingPlayer = existingData[playerIndex];
            existingPlayer.result.role_data = updateRoleData(
                existingPlayer.result.role_data,
                newData.result.role_data
            );
            existingPlayer.tips = newData.tips || existingPlayer.tips;
            existingPlayer.code = newData.code || existingPlayer.code;
            existingPlayer.result.name = newData.result.name || existingPlayer.result.name;
            existingPlayer.result.user_level = newData.result.user_level || existingPlayer.result.user_level;
        }
        
        await savePlayerData(existingData);
        console.log(`玩家 ${targetUid} 数据更新成功`);
        return existingData;
    } catch (error) {
        console.error('更新玩家数据失败:', error);
        throw error;
    }
}